import {
  getOrientation,
  getStageAndCourseByOrientationId,
  getStudentStageAndCourseByOrientationId,
  addCourse
} from "@/api/course/index";
import { imageUpload } from "@/api/common/index";
import { ref, onMounted, reactive, computed } from "vue";
import { ElMessage, type FormRules } from "element-plus";
import { QNURL } from "@/config/urlConfig";
import { useUserStoreHook } from "@/store/modules/user";
import type { UploadProps } from "element-plus";

export function useCourseManageHooks() {
  const userStore = useUserStoreHook();

  const userInfo = computed(() => userStore.userInfo);

  const isTeacher = computed(() => userStore.roles.includes("teacher"));

  const orientationList = ref<any>([]);

  const currentOrientationIndex = ref(0);
  const currentOrientationId = ref("");

  const currentStageId = ref("");

  async function getOrientationList() {
    const res = await getOrientation();

    orientationList.value = res.data.records;
    currentOrientationId.value = res.data?.records[0]?.id;

    getStageAndCourseByOrientationIdFun();
  }

  // ------------

  const courseList = ref<any>([]);

  async function getStageAndCourseByOrientationIdFun() {
    let res;
    if (isTeacher.value) {
      res = await getStageAndCourseByOrientationId({
        id: currentOrientationId.value,
        userId: userStore.getUserInfo?.userId
      });
    } else {
      res = await getStudentStageAndCourseByOrientationId({
        id: currentOrientationId.value,
        userId: userStore.getUserInfo?.userId
      });
    }

    courseList.value = res.data;
  }

  function orientationClick(item: any, index: number) {
    console.log(item);
    currentOrientationId.value = item.id;
    currentOrientationIndex.value = index;
    getStageAndCourseByOrientationIdFun();
  }

  // ------------------- 操作 --------------------
  // 添加课程
  async function addCourseHandel(item: any) {
    addCourseVisible.value = true;
    currentStageId.value = item.id;
  }

  interface CarouseInfo {
    courseIntroduce: string;
    stageId: string;
    name: string;
    cover: string;
    userId: string;
  }

  const addCourseVisible = ref(false);
  const ruleFormRef = ref();
  const carouseInfo = reactive<CarouseInfo>({
    courseIntroduce: "",
    stageId: "",
    name: "",
    userId: userInfo.value.userId || "",
    cover: ""
  });

  const rules = reactive<FormRules<CarouseInfo>>({
    name: [{ required: true, message: "请输入课程名称", trigger: "blur" }],
    cover: [{ required: true, message: "请上传课程封面", trigger: "blur" }],
    courseIntroduce: [
      { required: true, message: "请输入课程介绍", trigger: "blur" }
    ]
  });

  const imageUrl = ref("");
  // const pathUrl = ref("");

  const handleAvatarSuccess: UploadProps["onSuccess"] = (
    response: any,
    uploadFile: any
  ) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!);
    console.log(imageUrl.value);
  };

  const beforeAvatarUpload: UploadProps["beforeUpload"] = file => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isJpgOrPng) {
      ElMessage.error("只能上传 JPG/PNG 图片格式的文件");
      return false;
    }
    if (!isLt2M) {
      ElMessage.error("文件大小超过 2MB 的限制");
      return false;
    }

    // 使用自定义的方式上传文件
    const formData = new FormData();
    formData.append("image", file);

    uploadFile(formData);

    return false;
  };

  const uploadFile = async (formData: FormData) => {
    console.log(formData);
    // 自定义上传方法
    // 在这里可以使用你喜欢的方式发送文件上传请求，例如使用axios或者fetch
    // 替换为你自己的上传地址
    // const uploadUrl = "/upload";
    // 发送请求上传文件
    // 例如使用axios：
    try {
      const res = await imageUpload(formData);
      if (res.code === 200) {
        imageUrl.value = QNURL + res?.msg;
        carouseInfo.cover = res?.msg;
      }
    } catch (error) {
      console.error(error);
    }
  };

  async function comfirmHandel() {
    carouseInfo.stageId = currentStageId.value;
    const res = await addCourse(carouseInfo);
    console.log(res);

    if (res.code == 200) {
      ruleFormRef.value.resetFields();
      getStageAndCourseByOrientationIdFun();
      ElMessage.success("添加成功");
      addCourseVisible.value = false;
    }
  }

  onMounted(() => {
    getOrientationList();
  });

  return {
    currentOrientationIndex,
    orientationList,
    courseList,
    rules,
    addCourseVisible,
    ruleFormRef,
    isTeacher,
    carouseInfo,
    comfirmHandel,
    orientationClick,
    addCourseHandel,
    handleAvatarSuccess,
    beforeAvatarUpload
  };
}
